/**
 * @author trex279
 */

 function readJsonFromFile(fileName){
	var file = air.File.applicationStorageDirectory.resolvePath(fileName);
	
	if(!file.exists){
		return -1;
	}
	
	var myfileStream = new air.FileStream();
	
	myfileStream.open(file, air.FileMode.READ);
	
	myfileStream.addEventListener(air.Event.COMPLETE, completeHandler);
	myfileStream.addEventListener(air.IOErrorEvent.IO_ERROR, errorHandler);
	myfileStream.addEventListener(air.Event.CLOSE, closeHandler);
	
	
	var fileSize = parseInt(file.size);
	var oldJson = myfileStream.readMultiByte(fileSize, "iso-8859-1");
	
	
	myfileStream.close();
	 
	function completeHandler(event) 
	{ 
	    
	}
	function errorHandler(event) 
	{ 
	    alert("Error occurred"); // convert to jquery dialog
	    return false;
	}
	function closeHandler(event) 
	{ 
		return true;
	   //alert("Filestream closed");
	}
	return oldJson;
}

function storeJson(data, fileName){ //returns true if successful, else returns false.
	var file = air.File.applicationStorageDirectory.resolvePath(fileName);
	var myfileStream = new air.FileStream();
	
	myfileStream.openAsync(file, air.FileMode.WRITE);
	
	myfileStream.addEventListener(air.Event.COMPLETE, completeHandler);
	myfileStream.addEventListener(air.IOErrorEvent.IO_ERROR, errorHandler);
	myfileStream.addEventListener(air.Event.CLOSE, closeHandler);
	
	var encoded = $.toJSON(data);
	
	myfileStream.writeMultiByte(encoded, "iso-8859-1");
	myfileStream.close();
	
	function completeHandler(event){
	
	}
	function errorHandler(event){
		alert("Error occurred"); // convert to jquery dialog
		return false;
	}
	function closeHandler(event){
		return true;
		//alert("Filestream closed");
	}
}

function toHtml(string){
	var e = document.createElement('div');
  	e.innerHTML = string;
  	return e.childNodes[0].nodeValue;
}

function readPreference(prefName){
	var file = air.File.applicationDirectory.resolvePath("prefs.xml");
	
	if(!file.exists){
		return -1;
	}
	
	var myfileStream = new air.FileStream();
	
	myfileStream.open(file, air.FileMode.READ);
	
	myfileStream.addEventListener(air.Event.COMPLETE, completeHandler);
	myfileStream.addEventListener(air.IOErrorEvent.IO_ERROR, errorHandler);
	myfileStream.addEventListener(air.Event.CLOSE, closeHandler);
	
	
	var fileSize = parseInt(file.size);
	
	var prefsXML = myfileStream.readUTFBytes(fileSize);
 	
	
	myfileStream.close();
	 
	function completeHandler(event) 
	{ 
	    
	}
	function errorHandler(event) 
	{ 
	    alert("Error occurred in reading preference file"); // convert to jquery dialog
	    return false;
	}
	function closeHandler(event) 
	{ 
		return true;
	   //alert("Filestream closed");
	}
	
	$.xmlDOM(prefsXML)
		.find('preference')
			.each(function(){
				if($(this).find('name').text()==prefName){
					return $(this).find('value').text();
				};
			});
	
	return;
}
